package com.ruoyi.merchant.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.merchant.domain.Merchant;
import com.ruoyi.merchant.domain.MerchantApplication2;
import com.ruoyi.merchant.domain.dto.MerchantApplicationRequest;
import com.ruoyi.merchant.domain.vo.MerchantApplicationResponse;
import com.ruoyi.merchant.mapper.MerchantApplication2Mapper;
import com.ruoyi.merchant.mapper.MerchantMapper;
import com.ruoyi.merchant.service.IMerchantApplication2Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MerchantApplication2ServiceImpl implements IMerchantApplication2Service {

    @Autowired
    private MerchantApplication2Mapper applicationMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MerchantApplicationResponse submitApplication(
            MerchantApplicationRequest request, Long merchantId) {

        log.info("商家{}提交入驻申请，邮箱：{}", merchantId, request.getContactEmail());

        // 1. 查询当前商家信息
        Merchant merchant = merchantMapper.selectMerchantById(merchantId);
        if (merchant == null) {
            throw new ServiceException("商家信息不存在");
        }

        // 2. 验证状态
        String currentStatus = StringUtils.defaultIfBlank(
                merchant.getExternField1(), "PENDING_INFO");

        if ("UNDER_REVIEW".equals(currentStatus)) {
            throw new ServiceException("您的申请正在审核中，请勿重复提交");
        }

        // 3. 查询该商家的已有申请记录
        MerchantApplication2 existingApplication = applicationMapper.selectByMerchantId(merchantId);
        log.info("查询已有申请记录结果：{}", existingApplication != null ?
                "找到记录ID=" + existingApplication.getApplicationId() : "未找到");

        // 4. 唯一性校验
        validateUniqueness(request, merchantId, existingApplication);

        // 5. 决定是插入还是更新
        Long applicationId;
        if (existingApplication != null && existingApplication.getApplicationId() != null) {
            applicationId = updateExistingApplication(request, merchant, existingApplication);
        } else {
            applicationId = createNewApplication(request, merchant, merchantId);
        }

        // 6. 更新商家状态
        updateMerchantStatus(merchantId);

        // 7. 返回结果
        return MerchantApplicationResponse.builder()
                .applicationId(applicationId)
                .applicationStatus(0)
                .statusDesc("待审核")
                .applicationTime(DateUtils.getTime())
                .estimateTime("1-3个工作日")
                .build();
    }

    /**
     * ⭐ 修复后的唯一性校验逻辑
     */
    private void validateUniqueness(MerchantApplicationRequest request,
                                    Long merchantId,
                                    MerchantApplication2 existingApplication) {

        // 校验营业执照唯一性
        MerchantApplication2 existLicense = applicationMapper.selectApplicationByLicense(
                request.getBusinessLicense());

        if (existLicense != null) {
            // 排除自己的记录
            if (!isSelfRecord(existLicense, merchantId, existingApplication)) {
                // ⭐ 安全地检查申请状态
                if (isValidApplication(existLicense)) {
                    throw new ServiceException("该营业执照号已被使用");
                }
            }
        }

        // 校验邮箱唯一性
        MerchantApplication2 existEmail = applicationMapper.selectApplicationByEmail(
                request.getContactEmail());

        if (existEmail != null) {
            // 排除自己的记录
            if (!isSelfRecord(existEmail, merchantId, existingApplication)) {
                // ⭐ 安全地检查申请状态
                if (isValidApplication(existEmail)) {
                    throw new ServiceException("该邮箱已被使用");
                }
            }
        }
    }

    /**
     * ⭐ 判断是否是自己的记录
     */
    private boolean isSelfRecord(MerchantApplication2 application,
                                 Long merchantId,
                                 MerchantApplication2 existingApplication) {
        Long existMerchantId = application.getMerchantId();
        Long existAppId = application.getApplicationId();

        // 通过 merchantId 或 applicationId 判断
        return (existMerchantId != null && existMerchantId.equals(merchantId))
                || (existingApplication != null && existAppId != null
                && existAppId.equals(existingApplication.getApplicationId()));
    }

    /**
     * ⭐ 判断是否是有效的申请（待审核或已通过）
     */
    private boolean isValidApplication(MerchantApplication2 application) {
        Integer status = application.getApplicationStatus();
        // status 为 null、0（待审核）、1（已通过）时返回 true
        return status != null && (status == 0 || status == 1);
    }

    /**
     * 更新已有申请记录
     */
    private Long updateExistingApplication(MerchantApplicationRequest request,
                                           Merchant merchant,
                                           MerchantApplication2 existingApplication) {
        log.info("更新已有申请记录，ID: {}", existingApplication.getApplicationId());

        MerchantApplication2 updateApp = new MerchantApplication2();
        updateApp.setApplicationId(existingApplication.getApplicationId());
        updateApp.setMerchantName(request.getMerchantName());
        updateApp.setMerchantType(request.getMerchantType());
        updateApp.setContactName(request.getContactName());
        updateApp.setContactPhone(merchant.getContactPhone());
        updateApp.setContactEmail(request.getContactEmail());
        updateApp.setAddress(request.getAddress());
        updateApp.setDescription(request.getDescription());
        updateApp.setBusinessLicense(request.getBusinessLicense());
        updateApp.setIdCardFront(request.getIdCardFront());
        updateApp.setIdCardBack(request.getIdCardBack());

        if (request.getOtherCredentials() != null && !request.getOtherCredentials().isEmpty()) {
            updateApp.setOtherCredentials(String.join(",", request.getOtherCredentials()));
        }

        updateApp.setAgreeAgreement(request.getAgreeAgreement() ? 1 : 0);
        updateApp.setApplicationStatus(0); // 重置为待审核
        updateApp.setApplicationTime(new Date());
        updateApp.setRejectReason(null);
        updateApp.setRemark(request.getRemark());

        int rows = applicationMapper.updateApplication(updateApp);
        log.info("更新影响行数: {}", rows);

        if (rows <= 0) {
            throw new ServiceException("更新申请记录失败");
        }

        return existingApplication.getApplicationId();
    }

    /**
     * 创建新申请记录
     */
    private Long createNewApplication(MerchantApplicationRequest request,
                                      Merchant merchant,
                                      Long merchantId) {
        log.info("创建新申请记录");

        MerchantApplication2 application = new MerchantApplication2();
        application.setMerchantId(merchantId);
        application.setMerchantName(request.getMerchantName());
        application.setMerchantType(request.getMerchantType());
        application.setContactName(request.getContactName());
        application.setContactPhone(merchant.getContactPhone());
        application.setContactEmail(request.getContactEmail());
        application.setAddress(request.getAddress());
        application.setDescription(request.getDescription());
        application.setBusinessLicense(request.getBusinessLicense());
        application.setIdCardFront(request.getIdCardFront());
        application.setIdCardBack(request.getIdCardBack());

        if (request.getOtherCredentials() != null && !request.getOtherCredentials().isEmpty()) {
            application.setOtherCredentials(String.join(",", request.getOtherCredentials()));
        }

        application.setAgreeAgreement(request.getAgreeAgreement() ? 1 : 0);
        application.setApplicationStatus(0); // 待审核
        application.setApplicationTime(new Date());
        application.setRemark(request.getRemark());

        int rows = applicationMapper.insertApplication(application);
        if (rows <= 0) {
            throw new ServiceException("创建申请记录失败");
        }

        Long applicationId = application.getApplicationId();
        log.info("新创建的申请ID: {}", applicationId);
        return applicationId;
    }

    /**
     * 更新商家状态
     */
    private void updateMerchantStatus(Long merchantId) {
        Merchant updateMerchant = new Merchant();
        updateMerchant.setMerchantId(merchantId);
        updateMerchant.setExternField1("UNDER_REVIEW");

        int rows = merchantMapper.updateMerchant(updateMerchant);
        if (rows <= 0) {
            throw new ServiceException("更新商家状态失败");
        }
    }

    @Override
    public List<MerchantApplication2> getApplicationHistory(Long merchantId) {
        return applicationMapper.selectApplicationsByMerchantId(merchantId);
    }

    @Override
    public MerchantApplication2 getLatestApplication(Long merchantId) {
        return applicationMapper.selectLatestByMerchantId(merchantId);
    }
}
